package com.xhf.camera.cameraapp;

import android.app.Activity;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends Activity implements View.OnClickListener, SurfaceHolder.Callback{
    private SurfaceView camera_sf;
    private Button btn_take_photo;
    private Button btn_change_camera;
    private Button btn_back;
    //安卓硬件相机
    private Camera mCamera;
    private SurfaceHolder mHolder;
    public static final String FILE_PATH = "filePath";
    private int mCameraId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        previceCamera(mCamera, surfaceHolder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        mCamera.stopPreview();
        previceCamera(mCamera, surfaceHolder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            //停止预览
            mCamera.stopPreview();
            //释放相机资源
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.camera_sf://点击可以对焦
                if (null != mCamera)
                    mCamera.autoFocus(null);
                break;
            case R.id.btn_take_photo://点击进行拍照
                startTakephoto();
                break;
            case R.id.btn_change_camera://点击切换到前置摄像头
                try {
                    changeCamera();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_back:
                System.exit(0);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == mCamera) {
            mCamera = getCustomCamera();
            if (mHolder != null) {
                //开户相机预览
                previceCamera(mCamera, mHolder);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            //停止预览
            mCamera.stopPreview();
            //释放相机资源
            mCamera.release();
            mCamera = null;
        }
    }

    private Camera getCustomCamera() {
        if (null == mCamera) {
            //使用Camera的Open函数开机摄像头硬件
            mCamera = Camera.open();
            //Camera.open()方法说明：2.3以后支持多摄像头，所以开启前可以通过getNumberOfCameras先获取摄像头数目，
            // 再通过 getCameraInfo得到需要开启的摄像头id，然后传入Open函数开启摄像头，
            // 假如摄像头开启成功则返回一个Camera对象
        }
        return mCamera;
    }

    private void previceCamera(Camera camera, SurfaceHolder holder) {
        try {
            setupCamera();
            //摄像头设置SurfaceHolder对象，把摄像头与SurfaceHolder进行绑定
            camera.setPreviewDisplay(holder);
            //调整系统相机拍照角度
            setCameraDisplayOrientation(this, mCameraId, mCamera);
            //调用相机预览功能
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initViews() {
        this.camera_sf = (SurfaceView) findViewById(R.id.camera_sf);
        this.btn_take_photo = (Button) findViewById(R.id.btn_take_photo);
        this.btn_change_camera = findViewById(R.id.btn_change_camera);
        this.btn_back = findViewById(R.id.btn_back);
        this.btn_take_photo.setOnClickListener(this);
        this.btn_back.setOnClickListener(this);
        camera_sf.setOnClickListener(this);
        btn_take_photo.setOnClickListener(this);
        btn_change_camera.setOnClickListener(this);
        //获取SurfaceView的SurfaceHolder对象
        mHolder = camera_sf.getHolder();
        //实现SurfaceHolder.Callback接口
        mHolder.addCallback(this);

    }

    private void startTakephoto() {
        //设置自动对焦
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    mCamera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                            dealWithCameraData(data);
                        }
                    });
                    mCamera.cancelAutoFocus();
                }
            }
        });
    }

    //保存拍照数据
    private void dealWithCameraData(byte[] data) {
        FileOutputStream fos = null;
        String tempStr = "/sdcard/ldm/";
        File file = new File(tempStr);
        if (!file.exists()) {
            file.mkdir();
        }
        //图片临时保存位置
        String fileName = tempStr + System.currentTimeMillis() + "_" + mCameraId + ".jpg";
        File tempFile = new File(fileName);
        try {
            fos = new FileOutputStream(fileName);
            //保存图片数据
            fos.write(data);
            fos.close();
            Intent intent = new Intent(MainActivity.this, ShowResultActivity.class);
            intent.putExtra(FILE_PATH, fileName);
            //setPictureDegreeZero(fileName);
            startActivity(intent);
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Camera openCamera(int type){
        Camera camera = null;
        try {
            camera = Camera.open(type);
        } catch (Exception e) {

        }
        return camera;
    }

    private void changeCamera() throws IOException{
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        mCameraId = (mCameraId + 1) % mCamera.getNumberOfCameras();
        mCamera = openCamera(mCameraId);
        if (mHolder != null) {
            previceCamera(mCamera, mHolder);
        }
    }

    public void setCameraDisplayOrientation(Activity activity,
                                            int cameraId, Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    private void setupCamera() {
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.set("rotation", 180);
        parameters.setPictureFormat(ImageFormat.JPEG);
        parameters.setPreviewSize(1440, 1080);
        parameters.setPictureSize(1440,  1080);
        mCamera.setParameters(parameters);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    }
}
